package com.meilele.controller.hongdian;

import com.meilele.util.zhengchao.Contants;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.OutputStream;

@Controller
@RequestMapping("/image")
public class ImageController {
    @RequestMapping("/download")
    public void download(String image , HttpServletResponse response){
        //attachment;filename=  filename后面跟着的等号(=)不能省略
        response.setHeader("Content-Disposition", "attachment;filename=" + image);
        show(image, response);
    }

    @RequestMapping("/show")
    public void show(String image , HttpServletResponse response){
        //根据文件的名字，去得到文件的路径
        File file = new File(Contants.IMAGE_PATH + image);
        if(file.exists()) {
            try {
                FileInputStream input = new FileInputStream(file);
                OutputStream out = response.getOutputStream();
                byte[] data = new byte[1024];
                int len = 0;
                while ((len = input.read(data)) != -1) {
                    out.write(data, 0, len);
                }
                input.close();
                out.flush();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
